﻿using JNPF.Basics.Models;
using JNPF.Basics.Models.WorkFlow.Dtos.FlowTask;
using JNPF.Basics.Models.WorkFlow.Model;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic.WorkFlow.FlowFlowDynamic
{
    public class FlowFlowDynamicBll
    {
        private FlowEngineBll flowEngineBll = new FlowEngineBll();
        private BillRuleBll billRuleBll = new BillRuleBll();
        private OrganizeBll organizeBll = new OrganizeBll();
        UserBll userBll = new UserBll();
        private PositionBll positionBll = new PositionBll();
        private FlowFlowDynamicService dynamicservice = new FlowFlowDynamicService();
        private FlowTaskBll flowTaskBll = new FlowTaskBll();
        //private VisualDevModelDataService visualDevModelDataService = new VisualDevModelDataService();

        public async Task<FlowTaskInfoOutput> Info(FlowTaskEntity entity)
        {
            try
            {
                var flowentity = await flowEngineBll.GetInfo(entity.FlowId);
                var tableModelList = flowentity.Tables.ToList<FlowTableModel>();
                FlowTaskInfoOutput output = entity.MapTo<FlowTaskInfoOutput>();
                //formTempJson
                #region 将fields字段值序列化
                var jobj = flowentity.FormTemplateJson.ToObject();//表单模板信息
                if (jobj != null)
                {
                    jobj["fields"] = JsonHelper.ToJson(jobj["fields"]);
                }
                #endregion
                FormDataModel formData = jobj.ToObject<FormDataModel>();
                List<FieldsModel> list = formData.fields.ToList<FieldsModel>();
                //主表字段的jnpfkey
                Dictionary<string, string> mast = new Dictionary<string, string>();
                //子表字段的jnpfkey
                Dictionary<string, Dictionary<string, string>> table = new Dictionary<string, Dictionary<string, string>>();
                Dictionary<string, object> result = new Dictionary<string, object>();
                if (tableModelList.Count > 0)
                {
                    //流程设计关联表
                    string mastTableName = tableModelList.Find(x => "1".Equals(x.typeId)).table;
                    List<FlowTableModel> tableListAll = tableModelList.FindAll(x => !"1".Equals(x.typeId));
                    // 子表获取表单对应的key
                    Dictionary<string, string> tableModelKey = new Dictionary<string, string>();
                    //封装数据
                    tempJson(list, mast, table, tableModelKey, 1);
                    StringBuilder mastInfo = new StringBuilder("select * from " + mastTableName + " where F_ID='" + entity.Id + "'");
                    Dictionary<string, object> mastData = dynamicservice.getMast(mastInfo.ToString());
                    //主表数据
                    foreach (var key in mast.Keys.ToArray())
                    {
                        string jnpfkey = mast.GetValue(key);
                        object dataValue = mastData.ContainsKey(key.ToLower()) ? mastData[key.ToLower()] : "";
                        object value = assigments(jnpfkey, dataValue, 2, mast, key, 0, list).Result;
                        result.Add(key, value);
                    }
                    //子表数据
                    foreach (var tableModel in tableListAll.ToArray())
                    {
                        var tableName = tableModel.table;
                        StringBuilder tableInfo = new StringBuilder("select * from " + tableName + " where " + tableModel.tableField + "='" + entity.Id + "'");
                        var tableList = dynamicservice.getTableDataInfo(tableInfo.ToString());
                        var tableResult = new List<Dictionary<string, object>>();
                        var tableJnpf = table[tableName];
                        foreach (var tableInfoModel in tableList.ToArray())
                        {
                            var tablValue = new Dictionary<string, object>();
                            foreach (var key in tableJnpf.Keys.ToArray())
                            {
                                var childkey = tableJnpf[key];
                                var childValue = tableInfoModel[key.ToLower()];
                                var value = assigments(childkey, childValue, 2, tableJnpf, key, 0,list).Result;
                                tablValue.Add(key, value);
                            }
                            tableResult.Add(tablValue);
                        }
                        if (tableModelKey.ContainsKey(tableName) && tableModelKey[tableName].IsNotEmptyOrNull())
                        {
                            result.Add(tableModelKey[tableName], tableResult);
                        }
                    }
                    output.data = result.ToJson();
                }
                else
                {
                    //封装数据
                    tempJson(list, mast, table);
                    Dictionary<string, object> dataMap = entity.FlowFormContentJson.ToObject<Dictionary<string, object>>();
                    foreach (var key in dataMap.Keys.ToArray())
                    {
                        var jnpfkey = mast.GetValue(key);
                        if (jnpfkey != null)
                        {
                            var value = dataMap.ContainsKey(key) ? dataMap[key] : null;
                            var dataValue =  assigments(jnpfkey, value, 2, mast, key, 1,list).Result;
                            result.Add(key, dataValue);
                        }
                        else
                        {
                            Dictionary<string, string> childJnpfKey = table.ContainsKey(key) ? table[key] : new Dictionary<string, string>();
                            List<Dictionary<string, object>> childList = dataMap[key].ToJson().ToList<Dictionary<string, object>>();
                            foreach (var childMap in childList.ToArray())
                            {
                                foreach (string child in childMap.Keys.ToArray())
                                {
                                    var childkey = childJnpfKey.GetValue(child);
                                    var childValue = childMap.ContainsKey(child) ? childMap[child] : null;
                                    var dataValue =  assigments(childkey, childValue, 2, childJnpfKey, child, 1,list).Result;
                                    childMap[child] = dataValue;
                                }
                            }
                            result.Add(key, childList);
                        }
                    }
                    output.data = result.ToJson();
                }
                return output;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public async Task Save(string id, string flowId, string data,int writetype=0)
        {
            try
            {
                var entity = await flowEngineBll.GetInfo(flowId);
                UserInfo userInfo = UserProvider.Instance.Get();
                string billNo = "单据规则不存在";
                string title = userInfo.UserName + "的" + entity.FullName;
                string formId = CommonHelper.Guid;
                //formTempJson
                #region 将fields字段值序列化
                var jobj = entity.FormTemplateJson.ToObject();//表单模板信息
                if (jobj != null)
                {
                    jobj["fields"] = JsonHelper.ToJson(jobj["fields"]);
                }
                #endregion
                //表单模板信息
                FormDataModel formData = jobj.ToObject<FormDataModel>();
                //表单模板样式列集合
                List<FieldsModel> list = formData.fields.ToList<FieldsModel>();
                int type = 0;
                if (id != null)
                {
                    formId = id;
                    type = 1;
                }
                else
                {
                    FieldsModel fieLdsModel = list.Find(x => "billRule".Equals(x.__config__.jnpfKey));
                    if (fieLdsModel != null)
                    {
                        string ruleKey = fieLdsModel.__config__.rule;
                        billNo = await billRuleBll.GetBillNumber(ruleKey, false);
                    }
                }
                //表单值
                Dictionary<string, object> dataMap = data.ToObject<Dictionary<string, object>>();
                //关联表信息
                List<FlowTableModel> tableModelList = entity.Tables.ToList<FlowTableModel>();
                //主表字段的jnpfkey
                Dictionary<string, string> mast = new Dictionary<string, string>();
                //子表字段的jnpfkey
                Dictionary<string, Dictionary<string, string>> table = new Dictionary<string, Dictionary<string, string>>();
                if (tableModelList.Count > 0)
                {
                    string mastTableName = tableModelList.Find(x => "1".Equals(x.typeId)).table;//关联表名
                    //提交数据对应的子表
                    Dictionary<string, string> tableModel = new Dictionary<string, string>();
                    //封装数据
                    tempJson(list, mast, table, tableModel, 0);
                    if (id == null)
                    {
                        //最后的sql语句
                        string resultSql = ResultSql(mastTableName, formId, dataMap, tableModelList, mast, table, tableModel, type,list);
                        dynamicservice.opaTableDataInfo(resultSql);
                    }
                    else
                    {
                        //最后的sql语句
                        string resultSql = ResultSql(mastTableName, formId, dataMap, tableModelList, mast, table, tableModel, type,list);
                        dynamicservice.opaTableDataInfo(resultSql);
                    }
                    //流程信息
                    await flowTaskBll.Save(id, flowId, formId, title, 1, billNo, writetype);
                }
                else
                {
                    //封装数据
                    tempJson(list, mast, table);
                    foreach (var key in dataMap.Keys.ToArray())
                    {

                        if (mast.ContainsKey(key) && mast[key].IsNotEmptyOrNull())
                        {
                            var jnpfkey = mast[key];
                            var value = dataMap[key];
                            var dataValue = assigments(jnpfkey, value, type, mast, key, 1,list).Result;
                            dataMap[key] = dataValue;
                        }
                        else
                        {
                            var childJnpfKey = table[key];
                            var childList = dataMap[key].ToJson().ToList<Dictionary<string, object>>();
                            foreach (var childMap in childList.ToArray())
                            {
                                foreach (var child in childMap.Keys.ToArray())
                                {
                                    var childkey = childJnpfKey[child];
                                    var childValue = childMap[child];
                                    var dataValue = assigments(childkey, childValue, type, childJnpfKey, childkey, 1,list).Result;
                                    childMap[child] = dataValue;
                                }
                            }
                        }
                    }
                    data = dataMap.ToJson(); ;
                    //流程信息
                    await flowTaskBll.Save(id, flowId, formId, title, 1, billNo, data, writetype);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public async Task Submit(string id, string flowId, string data, string freeUserId)
        {
            try
            {

                FlowEngineEntity entity = await flowEngineBll.GetInfo(flowId);
                UserInfo info = UserProvider.Instance.Get();
                string billNo = "单据规则不存在";
                string title = info.UserName + "的" + entity.FullName;
                string formId = CommonHelper.Guid;
                //formTempJson
                #region 将fields字段值序列化
                var jobj = entity.FormTemplateJson.ToObject();
                if (jobj != null)
                {
                    jobj["fields"] = JsonHelper.ToJson(jobj["fields"]);
                }
                #endregion
                FormDataModel formData = jobj.ToObject<FormDataModel>();
                List<FieldsModel> list = formData.fields.ToList<FieldsModel>();
                int type = 0;
                if (id != null)
                {
                    formId = id;
                    type = 1;
                }
                else
                {
                    FieldsModel fieLdsModel = list.Find(x => "billRule".Equals(x.__config__.jnpfKey));
                    if (fieLdsModel != null)
                    {
                        string ruleKey = fieLdsModel.__config__.rule;
                        billNo = await billRuleBll.GetBillNumber(ruleKey, false);
                    }
                }

                //表单值
                Dictionary<string, object> dataMap = data.ToObject<Dictionary<string, object>>();
                //tableJson
                List<FlowTableModel> tableModelList = entity.Tables.ToList<FlowTableModel>();
                //主表字段的jnpfkey
                Dictionary<string, string> mast = new Dictionary<string, string>();
                //子表字段的jnpfkey
                Dictionary<string, Dictionary<string, string>> table = new Dictionary<string, Dictionary<string, string>>();
                if (tableModelList.Count > 0)
                {
                    string mastTableName = tableModelList.Find(x => "1".Equals(x.typeId)).table;
                    //提交数据对应的子表
                    Dictionary<string, string> tableModel = new Dictionary<string, string>();
                    //封装数据
                    tempJson(list, mast, table, tableModel, 0);
                    if (id == null)
                    {
                        //最后的sql语句
                        string resultSql = ResultSql(mastTableName, formId, dataMap, tableModelList, mast, table, tableModel, type,list);
                        dynamicservice.opaTableDataInfo(resultSql);
                    }
                    else
                    {
                        //最后的sql语句
                        string resultSql = ResultSql(mastTableName, formId, dataMap, tableModelList, mast, table, tableModel, type,list);
                        dynamicservice.opaTableDataInfo(resultSql);
                    }
                    //流程信息
                    await flowTaskBll.Submit(id, flowId, formId, title, 1, billNo, dataMap, freeUserId);
                }
                else
                {
                    //封装数据
                    tempJson(list, mast, table);
                    foreach (var key in dataMap.Keys.ToArray())
                    {

                        if (mast.ContainsKey(key) && mast[key].IsNotEmptyOrNull())
                        {
                            var jnpfkey = mast[key];
                            var value = dataMap[key];
                            var dataValue = assigments(jnpfkey, value, type, mast, key, 1,list).Result;
                            dataMap[key] = dataValue;
                        }
                        else
                        {
                            var childJnpfKey = table[key];
                            var childList = dataMap[key].ToJson().ToList<Dictionary<string, object>>();
                            foreach (var childMap in childList.ToArray())
                            {
                                foreach (var child in childMap.Keys.ToArray())
                                {
                                    var childkey = childJnpfKey[child];
                                    var childValue = childMap[child];
                                    var dataValue = assigments(childkey, childValue, type, childJnpfKey, childkey, 1,list).Result;
                                    childMap[child] = dataValue;
                                }
                            }
                        }
                    }
                    //流程信息
                    await flowTaskBll.Submit(id, flowId, formId, title, 1, billNo, dataMap, freeUserId);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #region Method
        /// <summary>
        /// 根据样式属性处理成不同类型数据
        /// </summary>
        /// <param name="jnpfkey"></param>
        /// <param name="dataValue"></param>
        /// <param name="type">0：保存，1：修改，2：查看</param>
        /// <param name="mast"></param>
        /// <param name="rule"></param>
        /// <param name="tableType">0：有表，1：无表</param>
        /// <returns></returns>
        private async Task<object> assigments(string jnpfkey, object dataValue, int type, Dictionary<string, string> mast, string rule, int tableType, List<FieldsModel> fieldsModelList)
        {
            try
            {
                var list= TemplateDataConversion(fieldsModelList);
                var fieldsModel = list.Find(x=>x.__vModel__== rule);
                var userInfo = UserProvider.Instance.Get();
                List<UserEntity> userAll = await userBll.GetList();
                object value = dataValue;
                if (value.IsNullOrEmpty())
                {
                    value = "";
                }
                switch (jnpfkey)
                {
                    //单据规则
                    case "billRule":
                        if (mast.ContainsKey(rule + "_rule"))
                        {
                            string ruleNo = await billRuleBll.GetBillNumber(mast[rule + "_rule"], false);
                            value = ruleNo;
                        }
                        break;
                    //创建用户    
                    case "createUser":
                        if (type == 0)
                        {
                            value = userInfo.UserId;
                        }
                        if (type == 1)
                        {
                            string userValue = value.ToString();
                            var model = userAll.Find(x => x.RealName.Equals(userValue));
                            value = "";
                            if (model != null)
                            {
                                value = model.Id;
                            }
                        }
                        if (type == 2)
                        {
                            string userValue = value.ToString();
                            var model = userAll.Find(x => x.Id.Equals(userValue));
                            value = "";
                            if (model != null)
                            {
                                value = model.RealName;
                            }
                        }
                        break;
                    //创建时间
                    case "createTime":
                        if (type == 0)
                        {
                            value = DateTime.Now;
                        }
                        if (type == 2)
                        {
                            value = value.ToDate();
                        }
                        break;
                    //修改用户
                    case "modifyUser":
                        if (type == 0)
                        {
                            value = "";
                        }
                        if (type == 1)
                        {
                            value = userInfo.UserId;
                        }
                        if (type == 2)
                        {
                            string userValue = value.ToString();
                            var model = userAll.Find(x => x.Id.Equals(userValue));
                            value = "";
                            if (model != null)
                            {
                                value = model.RealName;
                            }
                        }
                        break;
                    //创建时间
                    case "modifyTime":
                        if (type == 1)
                        {
                            value = DateTime.Now;
                        }
                        if (type == 0)
                        {
                            value = null;
                        }
                        if (type == 2)
                        {
                            value = value.ToDate();
                        }
                        break;
                    //所属部门
                    case "currDept":
                        if (type == 0)
                        {
                            value = userInfo.OrganizeId;
                        }
                        if (type == 1)
                        {
                            string depName = value.ToString();
                            var model = userAll.Find(x => organizeBll.GetName(x.OrganizeId).Equals(depName));
                            value = "";
                            if (model != null)
                            {
                                value = model.OrganizeId;
                            }
                        }
                        if (type == 2)
                        {
                            value = organizeBll.GetName(value.ToString());
                        }
                        break;
                    //所属岗位
                    case "currPosition":
                        UserEntity userEntity = userAll.Find(x => x.Id.Equals(userInfo.UserId));
                        PositionEntity positionEntity = await positionBll.GetInfo(userEntity.PositionId.Split(",")[0]);
                        if (type == 0)
                        {
                            value = positionEntity != null ? positionEntity.Id : "";
                        }
                        if (type == 1)
                        {
                            value=(await positionBll.GetList()).Find(x => x.FullName.Equals(value.ToString())).Id;
                        }
                        if (type == 2)
                        {
                            value = positionBll.GetName(value.ToString());
                        }
                        break;
                    //附件
                    case "uploadFz":
                        if (type == 2)
                        {
                            //附件
                            value = value.ToString().ToList<Dictionary<string, object>>();
                        }
                        break;
                    //图片
                    case "uploadImg":
                        if (type == 2)
                        {
                            //附件
                            value = value.ToString().ToList<Dictionary<string, object>>();
                        }
                        break;
                    case "checkbox":
                        if (type == 2)
                        {
                            value = value.ToString().ToList<string>();
                        }
                        break;
                    case "cascader":
                        if (type == 2)
                        {
                            value = value.ToString().ToList<object>();
                        }
                        break;
                    case "dateRange":
                        if (type == 2)
                        {
                            value = value.ToString().ToList<string>();
                        }
                        break;
                    case "timeRange":
                        if (type == 2)
                        {
                            value = value.ToString().ToList<string>();
                        }
                        break;
                    case "date":
                        if (tableType == 0 && value.IsNotEmptyOrNull())
                        {
                            if (type == 0 || type == 1)
                            {
                                value = string.Format("{0:yyyy-MM-dd HH:mm:ss}", CommonHelper.GetDateTime(value.ToString()));
                            }
                            if (type == 2)
                            {
                                value = CommonHelper.TimeToTimeStamp(value.ToString().ToDate());
                            }
                        }
                        break;
                    //颜色选择
                    case "colorPicker":
                        {
                            value = string.IsNullOrEmpty(value.ToString()) ? null : value.ToString();
                        }
                        break;
                    //评分
                    case "rate":
                        {
                            value = value.ToInt();
                        }
                        break;
                    //开关
                    case "switch":
                        {
                            value = value.ToInt();
                        }
                        break;
                    //滑块
                    case "slider":
                        {
                            if (fieldsModel.range)
                            {
                                value = value.ToString().ToObject<List<int>>();
                            }
                            else
                            {
                                value = value.ToInt();
                            };
                        }
                        break;
                    //富文本
                    case "editor":
                        {
                            value = string.IsNullOrEmpty(value.ToString()) ? null : value.ToString();
                        }
                        break;
                    //公司组件
                    case "comSelect":
                        {
                            if (!string.IsNullOrEmpty(value.ToString())&& fieldsModel.IsNotEmptyOrNull())
                            {
                                if (fieldsModel.multiple)
                                {
                                    value = value.ToString();
                                }
                                else
                                {
                                    value = value.ToString();
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        break;
                    //单选框组
                    case "radio":
                        {
                            value = string.IsNullOrEmpty(value.ToString()) ? null : value.ToString();
                        }
                        break;
                    //部门组件
                    case "depSelect":
                        {
                            if (!string.IsNullOrEmpty(value.ToString()) && fieldsModel.IsNotEmptyOrNull())
                            {
                                if (fieldsModel.multiple)
                                {
                                    value = value.ToString();
                                }
                                else
                                {
                                    value = value.ToString();
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        break;
                    //岗位组件
                    case "posSelect":
                        {
                            if (!string.IsNullOrEmpty(value.ToString()) && fieldsModel.IsNotEmptyOrNull())
                            {
                                if (fieldsModel.multiple)
                                {
                                    value = value.ToString();
                                }
                                else
                                {
                                    value = value.ToString();
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        break;
                    //用户组件
                    case "userSelect":
                        {
                            if (!string.IsNullOrEmpty(value.ToString()) && fieldsModel.IsNotEmptyOrNull())
                            {
                                if (fieldsModel.multiple)
                                {
                                    value = value.ToString();
                                }
                                else
                                {
                                    value = value.ToString();
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        break;
                    //树形选择
                    case "treeSelect":
                        {
                            if (!string.IsNullOrEmpty(value.ToString()))
                            {
                                if (fieldsModel.IsNotEmptyOrNull() && fieldsModel.multiple)
                                {
                                    value = value.ToString().Split(',').ToList<string>();
                                }
                                else
                                {
                                    value = value.ToString();
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        break;
                    //省市区联动
                    case "address":
                        {
                            if (type == 2)
                            {
                                value = value.ToString().ToList<string>();
                            }
                            //value = value.ToString().ToObject<List<string>>();
                        }
                        break;
                    //所属公司
                    case "currOrganize":
                        if (type == 0)
                        {
                            value = organizeBll.GetCompany(userInfo.OrganizeId).Result;
                        }
                        if (type == 1)
                        {
                            string organizeName = value.ToString();
                            var model =(await organizeBll.GetList()).Find(x=>x.FullName.Equals(organizeName));
                            value = "";
                            if (model != null)
                            {
                                value = model.Id;
                            }
                        }
                        if (type == 2)
                        {
                            value = value.ToString();
                        }
                        break;
                    //单行输入
                    case "comInput":
                        {
                            value = string.IsNullOrEmpty(value.ToString()) ? null : value.ToString();
                        }
                        break;
                    //多行输入
                    case "textarea":
                        {
                            value = value.ToString();
                        }
                        break;
                    //数字输入
                    case "numInputc":
                        {
                            value = value.ToInt();
                        }
                        break;
                    //金额输入
                    case "JNPFAmount":
                        {
                            value = value.ToDecimal();
                        }
                        break;
                    //下拉选择
                    case "select":
                        {
                            if (fieldsModel.IsNotEmptyOrNull()&& fieldsModel.multiple)
                            {
                                value = value.ToString().ToObject<List<string>>();
                            }
                            else
                            {
                                value = value.ToString();
                            }
                        }
                        break;
                    default:
                        if (value.IsNotEmptyOrNull())
                        {
                            value = value.ToString();
                        }
                        break;
                }
                return value;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 封装主表数据类型
        /// </summary>
        /// <param name="list">表单样式集合</param>
        /// <param name="mastTable">主表字段的jnpfkey</param>
        /// <param name="table">子表样式字段的jnpfkey</param>
        /// <param name="tableModel"></param>
        /// <param name="type"></param>
        private void tempJson(List<FieldsModel> list, Dictionary<string, string> mastTable, Dictionary<string, Dictionary<string, string>> table, Dictionary<string, string> tableModel, int type)
        {
            foreach (var fieLdsModel in list)
            {
                //样式属性
                string jnpfkey = fieLdsModel.__config__.jnpfKey;
                //样式属性字段
                string model = fieLdsModel.__vModel__;
                //是否设计子表
                if (!"table".Equals(jnpfkey))
                {
                    mastTable.Add(model, jnpfkey);
                    if ("billRule".Equals(jnpfkey))
                    {
                        string mastRule = fieLdsModel.__config__.rule;//子表表名（对应系统表）
                        mastTable.Add(model + "_rule", mastRule);
                    }
                }
                else
                {
                    //关联子表表名
                    string tableName = fieLdsModel.__config__.tableName;
                    if (type == 0)
                    {
                        tableModel.Add(model, tableName);
                    }
                    else
                    {
                        tableModel.Add(tableName, model);
                    }
                    tableTempJson(tableName, fieLdsModel.__config__.children, table);
                }
            }
        }

        /// <summary>
        /// 封装子表数据类型
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="childlist"></param>
        /// <param name="table"></param>
        private void tableTempJson(string tableName, List<Models.VisualDev.FieldsModel> childlist, Dictionary<string, Dictionary<string, string>> table)
        {
            try
            {
                if (childlist.IsNotEmptyOrNull()&& childlist.Count>0)
                {
                    Dictionary<string, string> childField = new Dictionary<string, string>();
                    foreach (var fieLdsModel in childlist)
                    {
                        string jnpfkey = fieLdsModel.__config__.jnpfKey;
                        string model = fieLdsModel.__vModel__;
                        childField.Add(model, jnpfkey);
                        if ("billRule".Equals(jnpfkey))
                        {
                            string mastRule = fieLdsModel.__config__.rule;
                            childField.Add(model + "_rule", mastRule);
                        }
                    }
                    table.Add(tableName, childField);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        private void tempJson(List<FieldsModel> list, Dictionary<string, string> mastTable, Dictionary<string, Dictionary<string, string>> table)
        {
            try
            {
                foreach (var fieLdsModel in list)
                {
                    var jnpfkey = fieLdsModel.__config__.jnpfKey;
                    var model = fieLdsModel.__vModel__;
                    if (!"table".Equals(jnpfkey)&& model.IsNotEmptyOrNull())
                    {
                        mastTable.Add(model, jnpfkey);
                        if ("billRule".Equals(jnpfkey))
                        {
                            var mastRule = fieLdsModel.__config__.rule;
                            mastTable.Add(model + "_rule", mastRule);
                        }
                    }
                    else
                    {
                        tableTempJson(model, fieLdsModel.__config__.children, table);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private string ResultSql(string mastTableName, string formId, Dictionary<string, object> dataMap, List<FlowTableModel> tableModelList, Dictionary<string, string> mast, Dictionary<string, Dictionary<string, string>> table, Dictionary<string, string> tableModel, int type,List<FieldsModel> fieldsModelsList)
        {
            try
            {
                //删除语句
                StringBuilder delMast = new StringBuilder("delete from " + mastTableName + " where F_ID='" + formId + "';");
                StringBuilder deletetable = new StringBuilder();
                //主表拼接字段
                StringBuilder mastSql = new StringBuilder("insert into " + mastTableName + " ");
                StringBuilder mastfile = new StringBuilder("(F_ID,");
                StringBuilder mastvalue = new StringBuilder("('" + formId + "',");
                //子表拼接字段
                StringBuilder tableSql = new StringBuilder();
                foreach (var key in dataMap.Keys.ToArray())
                {
                    if (mast.ContainsKey(key) && mast[key].IsNotEmptyOrNull())
                    {
                        var jnpfkey = mast[key];
                        var dataValue = dataMap[key];
                        mastfile.Append(key + ",");
                        var mastValue = assigments(jnpfkey, dataValue, type, mast, key, 0, fieldsModelsList).Result;
                        if (mastValue != null)
                        {
                            mastvalue.Append("'" + mastValue + "',");
                        }
                        else
                        {
                            mastvalue.Append("null,");
                        }
                        dataMap[key] = mastValue;
                    }
                    else
                    {
                        //获取table名称
                        string tableName = tableModel[key];
                        string mastFile = tableModelList.Find(x => x.table.Equals(tableName)).tableField;
                        Dictionary<string, string> tableJnpfKey = table[tableName];
                        List<Dictionary<string, object>> tableList = dataMap[key].ToString().ToList<Dictionary<string, object>>();
                        //子表字段
                        StringBuilder tableFiled = new StringBuilder("F_ID,");
                        //子表数据
                        StringBuilder tablevalue = new StringBuilder();
                        int num = 0;
                        foreach (var child in tableList.ToArray())
                        {

                            StringBuilder value = new StringBuilder();
                            StringBuilder Filed = new StringBuilder();
                            foreach (var childkey in child.Keys.ToArray())
                            {

                                //最后通过jnpfkey修改值
                                var childjnpfkey = tableJnpfKey[childkey];
                                var childvalue = child[childkey];
                                var chilValue = assigments(childjnpfkey, childvalue, type, tableJnpfKey, childkey, 0, fieldsModelsList).Result;
                                if (chilValue != null)
                                {
                                    value.Append("'" + chilValue + "',");
                                }
                                else
                                {
                                    value.Append(chilValue + ",");
                                }
                                child[childkey] = chilValue;
                            }
                            //添加字段
                            if (num == 0)
                            {
                                tableFiled.Append(string.Join(",", child.Keys.ToArray()) + ",");
                                num++;
                            }
                            if (value.Length > 0)
                            {
                                value = value.Remove(value.Length - 1, 1);
                                tablevalue.Append("('" + CommonHelper.Guid + "'," + value + ",'" + formId + "'),");
                            }
                        }
                        if (tablevalue.Length > 0)
                        {
                            tableFiled.Append(mastFile);
                            tablevalue = tablevalue.Remove(tablevalue.Length - 1, 1);
                            tableSql.Append("insert into " + tableName + "(" + tableFiled + ") values " + tablevalue + ";");
                        }
                        deletetable.Append("delete from " + tableName + " where " + mastFile + "='" + formId + "';");
                    }
                }
                //主表去掉最后
                mastfile = mastfile.Remove(mastfile.Length - 1, 1).Append(")");
                mastvalue = mastvalue.Remove(mastvalue.Length - 1, 1).Append(")");
                mastSql.Append(mastfile + " values " + mastvalue + ";");
                //最后语句
                StringBuilder resultSql = new StringBuilder();
                if (type == 0)
                {
                    resultSql.Append(mastSql.ToString() + tableSql);
                }
                else
                {
                    resultSql.Append(delMast + mastSql.ToString() + deletetable + tableSql);
                }
                return resultSql.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 模板数据转换
        /// </summary>
        /// <param name="fieldsModelList"></param>
        /// <returns></returns>
        public List<FieldsModel> TemplateDataConversion(List<FieldsModel> fieldsModelList)
        {
            var template = new List<FieldsModel>();
            //将模板内的无线children解析出来
            foreach (var item in fieldsModelList)
            {
                var config = item.__config__;
                switch (config.jnpfKey)
                {
                    //栅格布局
                    case "row":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children.ToJson().ToList<FieldsModel>()));
                        }
                        break;
                    //表格
                    case "table":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children.ToJson().ToList<FieldsModel>()));
                        }
                        break;
                    //卡片
                    case "card":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children.ToJson().ToList<FieldsModel>()));
                        }
                        break;
                    //文本
                    case "JNPFText":
                        break;
                    //分割线
                    case "divider":
                        break;
                    //分组标题
                    case "groupTitle":
                        break;
                    default:
                        {
                            template.Add(item);
                        }
                        break;
                }
            }
            return template;
        }

        /// <summary>
        /// 模板子集数据转换
        /// </summary>
        /// <param name="childrenList"></param>
        /// <returns></returns>
        public List<FieldsModel> TemplateChildrenDataConversion(List<FieldsModel> childrenList)
        {
            var template = new List<FieldsModel>();
            //将模板内的无线children解析出来
            foreach (var item in childrenList)
            {
                var config = item.__config__;
                switch (config.jnpfKey)
                {
                    //栅格布局
                    case "row":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children.ToJson().ToList<FieldsModel>()));
                        }
                        break;
                    //表格
                    case "table":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children.ToJson().ToList<FieldsModel>()));
                        }
                        break;
                    //卡片
                    case "card":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children.ToJson().ToList<FieldsModel>()));
                        }
                        break;
                    //文本
                    case "JNPFText":
                        break;
                    //分割线
                    case "divider":
                        break;
                    //分组标题
                    case "groupTitle":
                        break;
                    default:
                        {
                            template.Add(item);
                        }
                        break;
                }
            }
            return template;
        }
        #endregion
    }
}
